from odoo import api, fields, models
from odoo.exceptions import ValidationError


class ShipInstructionsWizard(models.TransientModel):
    _name = 'ship.instructions.wizard'
    _description = 'Ship Instructions Wizard'

    ship_instructions_id = fields.Many2one('ship.instructions')
    sale_order_id = fields.Many2one('sale.order')
    partner_id = fields.Many2one('res.partner')
    line_ids = fields.One2many('ship.instructions.line.wizard', 'wizard_id')
    sale_ids = fields.Many2many('sale.order', string='Sales')

    @api.onchange('sale_order_id')
    def onchange_line_ids(self):
        if not self.sale_order_id:
            return
        line_vals = []
        for line in self.sale_order_id.order_line:
            if line.product_template_id.detailed_type == 'product':
                line_vals.append((0, 0, {'sale_order_line_id': line.id}))
        self.line_ids = line_vals

    def action_confirm(self):
        for line in self.line_ids:
            if line.is_option:
                if line.delivery_qty > line.delivered_qty:
                    raise ValidationError('指派数不能大于待出货数')
                self.env['ship.instructions.line'].create({
                    'sale_order_id': self.sale_order_id.id,
                    'sale_order_line_id': line.sale_order_line_id.id,
                    'delivery_qty': line.delivery_qty,
                    'ship_instructions_id': self.ship_instructions_id.id})
        return {"type": "ir.actions.act_window_close"}


class ShipInstructionsLineWizard(models.TransientModel):
    _name = 'ship.instructions.line.wizard'
    _description = 'Ship Instructions Line Wizard'

    wizard_id = fields.Many2one('ship.instructions.wizard')
    is_option = fields.Boolean(string='Select')
    sale_order_line_id = fields.Many2one('sale.order.line')
    po_name = fields.Char(string='PO', related='sale_order_line_id.po')
    pn = fields.Char(string='PN', related='sale_order_line_id.pn')
    pn_rev = fields.Char(string='PN', related='sale_order_line_id.pn_rev')
    product_id = fields.Many2one('product.product', string='Product', related='sale_order_line_id.product_id')
    # 订单数
    product_uom_qty = fields.Float(string='Quantity', digits='Product Unit of Measure',
                                   related="sale_order_line_id.product_uom_qty")
    # 待出货数
    delivered_qty = fields.Float(string='Can Delivery Qty', digits='Product Unit of Measure',
                                 compute='_compute_delivered_qty')
    delivery_qty = fields.Float(string='Delivery Qty', digits='Product Unit of Measure', default=0)
    # 库存可用数
    qty_available = fields.Float(string='Available Qty', related='sale_order_line_id.free_qty',
                                 digits='Product Unit of Measure')

    def _compute_delivered_qty(self):
        for obj in self:
            obj.delivered_qty = obj.product_uom_qty - obj.sale_order_line_id.qty_delivered
